<!DOCTYPE html>
<html lang="en">
	<head>
		<meta charset="UTF-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
		<title>Document</title>
	</head>
	<body>
		<script>
			let activeEffect

			function effect(fn) {
				activeEffect = fn
				fn()
			}

			const bucket = new WeakMap()

			const data = { text: 'hello world' }

			const track = (target, key) => {
				if (!activeEffect) {
					return target[key]
				}

				// 1. 获取当前对象对应的依赖集合
				let depsMap = bucket.get(target)
        
				if (!depsMap) {
          depsMap = new Map()
					bucket.set(target, depsMap)
				}


				// 2. 获取当前属性对应的依赖集合
				let deps = depsMap.get(key)
        
				if (!deps) {
          deps = new Set()
					depsMap.set(key, deps)
				}
        

				deps.add(activeEffect)

			}

			const trigger = (target, key) => {
				// 1. 获取当前对象对应的依赖集合
				const depsMap = bucket.get(target)
				if (!depsMap) return

				// 2. 获取当前属性对应的依赖集合
				const effects = depsMap.get(key)

				// 3. 执行依赖函数
				effects && effects.forEach((fn) => fn())
			}

			const obj = new Proxy(data, {
				get(target, key) {
					track(target, key)

					return target[key]
				},

				set(target, key, newVal) {
					target[key] = newVal
					trigger(target, key)
				},
			})

			// effect(()=>{
			//   document.body.innerHTML = obj.text
			// })

			effect(() => {
				console.log(
					'%c [  ]-44',
					'font-size:13px; background:pink; color:#bf2c9f;',
					'effect run '
				)
				document.body.innerHTML = obj.text
			})

			setTimeout(() => {
				// obj.text = 'hello vue3'
				obj.noExist = 'hello vue3'

			}, 1000)
		</script>
	</body>
</html>
